package com.speed.controller;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonFactory;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.speed.entity.Activiter;
import com.speed.entity.Activtites;
import com.speed.entity.MenberCardStartactBm;
import com.speed.entity.SeatInfo;
import com.speed.interceptor.ActivitesInterceptor;
import com.speed.printer.PrintUtil;
import com.speed.printer.UserInfor;
import com.speed.service.ActiviterService;
import com.speed.service.ActivitesService;
import com.speed.service.MenberCardStarctBmService;
import com.speed.service.SeatService;
import com.speed.service.help.ActiviterImportHelper;
import com.speed.temp.SmsTempFactory;
import com.speed.util.GenerationSerialNo;
import com.speed.util.SmsFactory;
import com.speed.util.SmsTempData;
import com.speed.util.SmsTemplate;
import com.speed.util.StringUtils;
import com.speed.util.ecxel.ExcelResolver;
import com.speed.util.ecxel.ImportDataFactory;
import com.speed.util.ecxel.ImportTempData;
import com.speed.util.ecxel.TempData;
import com.speed.util.html.GenerStaticHTML;
import com.speed.util.html.TemplateData;
import com.speed.util.qc.MatrixToImageWriter;
import com.speed.vo.ActiviterVO;
import com.speed.vo.VoPageHelper;

/**
 * 管理员控制层：需要有admin管理权限的用户才能访问此控制器
 * 
 * @author ZhouChiJian
 *
 */
@Before(ActivitesInterceptor.class)
public class AdminController extends Controller {

	private static List<ActiviterVO> errVos = new ArrayList<ActiviterVO>();
	private static List<ActiviterVO> rightVos = new ArrayList<ActiviterVO>();

	public void list() {
		try {
			Integer page = getParaToInt(0);
			Integer activtitesID = getParaToInt(1);
			// 关键字查询
			String keyword = getPara(2);
			keyword = URLDecoder.decode(keyword==null?"":keyword, "utf-8");
			ActivitesService activitesService = enhance(ActivitesService.class);
			Activtites activtites = activitesService.findActivtitesById(activtitesID);
			setSessionAttr("activtites", activtites);
			int pageSize = 5;
			ActiviterService activiterService = enhance(ActiviterService.class);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put(Activiter.ACTIVITES_ID, activtitesID);

			if (StrKit.notBlank(keyword)) {
				// 手机末4位
				if (keyword.length() == 4 && StringUtils.isNumeric(keyword)) {
					params.put(Activiter.ACTIVITER_MOBILE, keyword);
					// 签到码
				} else if (keyword.length() == 8) {
					params.put(Activiter.SIGN_CODE, keyword);
					// 名称
				} else {
					params.put(Activiter.ACTIVITER_NAME, keyword);
				}
			}

			Page<Activiter> activiters = activiterService.findActivitersForPage(page, pageSize, params);
			setAttr("page", activiters);
			// 活动总人数
			Long totalMen = activiterService.getTotalActivitersByActivtitesID(activtitesID);
			setAttr("totalMen", totalMen == null ? 0 : totalMen);
			// 付费人数
			Long pays = activiterService.getPayedActiviters(Boolean.TRUE, activtitesID);
			setAttr("pays", pays == null ? 0 : pays);
			setAttr("isFirstPage", activiters.isFirstPage());
			setAttr("isLastPage", activiters.isLastPage());
			setAttr("temps", getSmsTempContents(activtitesID));
			renderJsp("list.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取短信模板内容
	 * 
	 * @param activtitesID
	 * @return
	 */
	private List<String> getSmsTempContents(Integer activtitesID) {
		List<String> tempsList = new ArrayList<String>();
		SmsTempFactory factory = SmsTempFactory.INSTANCE;

		List<String> tempName = factory.getTempName(activtitesID);
		if (tempName == null) {
			return Collections.EMPTY_LIST;
		}
		for (String name : tempName) {
			SmsTempData b = new SmsTempData();
			b.setName("陈某某");
			b.setSignCode("12345678");
			b.setMobile("13612345678");
			b.setActivites("某某活动");
			b.setMonth("3");
			b.setDay("25");
			b.setYear("2016");
			b.setPlacePoint("东莞市莞城区某某街道");
			b.setQrUrl("http://xxxx.yyyy.zzzzz");
			String content = factory.getContent(activtitesID, name, b);
			tempsList.add(content);
		}
		return tempsList;
	}

	public void add() {
		renderJsp("add.jsp");
	}

	@Before(POST.class)
	public void modify() {
		Long id = getParaToLong("id");
		String mobile = getPara("mobile");
		String name = getPara("name");
		String enterprise = getPara("enterprise");
		ActiviterService activiterService = enhance(ActiviterService.class);
		Map<String, Object> params = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		params.put(Activiter.ID, id);
		Activiter activiter = activiterService.getActiviterByCoditionForOne(params);
		if (activiter != null) {
			activiter.set(Activiter.ACTIVITER_MOBILE, mobile).set(Activiter.ACTIVITER_NAME, name)
					.set(Activiter.ENTERPRISE, enterprise).update();
		}
		json.put("msg", "保存成功!");
		json.put("status", "0");
		renderJson(json.toJSONString());
	}

	@Before(POST.class)
	public void sms() {
		String ids = getPara("ids");
		Integer tempIndex = getParaToInt("tempIndex");
		SmsTempFactory factory = SmsTempFactory.INSTANCE;

		ActiviterService activiterService = enhance(ActiviterService.class);
		Map<String, Object> params = new HashMap<String, Object>();
		int index = 0;
		String[] idsAry = ids.split(",");
		Activtites activtites = getSessionAttr("activtites");
		List<String> tempNames = factory.getTempName(activtites.getInt(Activtites.ID));
		for (String id : idsAry) {
			params.clear();
			params.put(Activiter.ID, id);
			Activiter activiter = activiterService.getActiviterByCoditionForOne(params);

			if (activiter != null) {
				String signCode = activiter.getStr(Activiter.SIGN_CODE);
				String mobile = activiter.getStr(Activiter.ACTIVITER_MOBILE);
				try {

					MatrixToImageWriter.genCode(signCode, mobile,
							PathKit.getWebRootPath() + File.separator + "code" + File.separator + mobile + ".jpg");
					TemplateData td = new TemplateData();
					// 活动人名
					td.setDatas("name", activiter.get(Activiter.ACTIVITER_NAME));
					td.setDatas("qdImg", mobile + ".jpg");
					td.setDatas("signCode", signCode);
					td.setDatas("mobile", mobile);
					td.setDatas("enterprise", activiter.get(Activiter.ENTERPRISE));
					// td.setDatas("sex", sex);
					td.setDatas("wrp", PropKit.get("staticURL") + "/code/" + mobile + ".html");
					td.setInPath(PathKit.getWebRootPath() + File.separator + "code");
					td.setOutPath(
							PathKit.getWebRootPath() + File.separator + "code" + File.separator + mobile + ".html");
					td.setTempName("qd.ftl");
					GenerStaticHTML.create(td);

				} catch (Exception e) {
					e.printStackTrace();
				}
				index++;
				SmsTempData data = new SmsTempData();
				data.setYear("2016");
				data.setMonth("3");
				data.setDay("31");
				data.setActivites(activtites.getStr(Activtites.ACTIVITES_NAME));
				data.setMobile(mobile);
				data.setName(activiter.getStr(Activiter.ACTIVITER_NAME));
				data.setSignCode(activiter.getStr(Activiter.SIGN_CODE));
				data.setPlacePoint(activtites.getStr(Activtites.ACTIVITES_ADDRESS));
				data.setQrUrl(PropKit.get("staticURL") + "/code/" + mobile + ".html");
				String content = factory.getContent(activtites.getInt(Activtites.ID), tempNames.get(tempIndex), data);
				SmsFactory.INSTANCE.send(activiter.getStr(Activiter.ACTIVITER_MOBILE), content);
			}
		}
		JSONObject json = new JSONObject();
		json.put("msg", "发送成功[" + index + "]");
		renderJson(json.toJSONString());
	}

	@Before(Tx.class)
	public void batchDel() {
		int index = 0;
		String ids = getPara("ids");
		ActiviterService activiterService = enhance(ActiviterService.class);
		String[] idsAry = ids.split(",");
		Map<String, Object> params = new HashMap<String, Object>();
		for (String id : idsAry) {
			index++;
			params.clear();
			params.put(Activiter.ID, id);
			Activiter activiter = activiterService.getActiviterByCoditionForOne(params);
			activiterService.delActiviter(activiter);
		}
		JSONObject json = new JSONObject();
		json.put("msg", "刪除成功[" + index + "]");
		renderJson(json.toJSONString());
	}

	@Before(Tx.class)
	public void del() {
		Integer id = getParaToInt("id");
		ActiviterService activiterService = enhance(ActiviterService.class);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(Activiter.ID, id);
		Activiter activiter = activiterService.getActiviterByCoditionForOne(params);
		boolean ok = activiterService.delActiviter(activiter);
		JSONObject json = new JSONObject();
		if (ok) {
			json.put("msg", "刪除成功!" + "{" + id + "}");
			json.put("status", "0");
		} else {
			json.put("status", "1");
			json.put("msg", "已删除");
		}
		renderJson(json.toJSONString());
	}

	public void file() {
		renderJsp("upload.jsp");
	}

	@Before({ POST.class })
	public void upload() {
		UploadFile file = getFile("excelFile");
		String isSkipStr = getAttr("isSkip");
		// 默认跳过第一行标题行
		boolean isSkip = StrKit.isBlank(isSkipStr) ? true : "1".equals(isSkipStr) ? true : false;
		List<ImportTempData> importTempDatas = null;
		importTempDatas = makeExcelType();
		try {
			File source = file.getFile();
			FileInputStream fis = new FileInputStream(source);
			List<TempData> tempDatas = ExcelResolver.importExcelData(fis, isSkip, importTempDatas);
			ActiviterImportHelper helper = importData(tempDatas);
			errVos.clear();
			rightVos.clear();
			errVos = helper.getVosByStatus("0");
			rightVos = helper.getVosByStatus("1");
			source.delete();
			data();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 直接绑定数据到前端页面
	 * 
	 * @param tempDatas
	 * @return
	 */
	private ActiviterImportHelper importData(List<TempData> tempDatas) {
		Activtites activtites = (Activtites) getSession().getAttribute("activtites");
		ActiviterService activiterService = enhance(ActiviterService.class);
		errVos.clear();
		rightVos.clear();
		ActiviterImportHelper helper = new ActiviterImportHelper(tempDatas, activiterService,
				activtites.getInt(Activtites.ID));
		return helper;
	}

	private List<ImportTempData> makeExcelType() {
		List<ImportTempData> tempDatas = new ArrayList<ImportTempData>();
		ImportDataFactory factory = ImportDataFactory.INSTANCE;
		tempDatas.add(factory.createImportTempData("name", 0));
		tempDatas.add(factory.createImportTempData("mobile", 1));
		tempDatas.add(factory.createImportTempData("enterprise", 2));
		tempDatas.add(factory.createImportTempData("sex", 3));
		return tempDatas;
	}

	/**
	 * 导入数据
	 */
	public void impt() {

		try {

			Timestamp timestamp = new Timestamp(new Date().getTime());
			String nowStr = String.valueOf(timestamp.getTime()).substring(0, 10);
			for (ActiviterVO vo : rightVos) {
				Activiter activiter = new Activiter();
				activiter.set(Activiter.ACTIVITER_NAME, vo.getName());
				activiter.set(Activiter.ACTIVITER_MOBILE, vo.getMobile());
				activiter.set(Activiter.SIGN_CODE, GenerationSerialNo.generNo());
				activiter.set(Activiter.SIGN_STATUS, Boolean.FALSE);
				Activtites activtites = (Activtites) getSession().getAttribute("activtites");
				activiter.set(Activiter.ACTIVITES_ID, activtites != null ? activtites.get(Activtites.ID) : null);
				// 默认为未支付
				activiter.set(Activiter.IS_PAY, Boolean.FALSE);
				activiter.set(Activiter.HD_ID, activtites != null ? activtites.get(Activtites.WXACT_ID) : null);
				activiter.save();

				MenberCardStarctBmService bmService = enhance(MenberCardStarctBmService.class);
				List<String> whereCodis = new ArrayList<String>();
				Ret ret = new Ret();
				ret.put(MenberCardStartactBm.RECORD_ID, activiter.get(Activiter.HD_ID));
				whereCodis.add(MenberCardStartactBm.RECORD_ID);
				ret.put(MenberCardStartactBm.MP, activiter.get(Activiter.ACTIVITER_MOBILE));
				whereCodis.add(MenberCardStartactBm.MP);
				// 暂时不联合姓名一起查
				// ret.put(MenberCardStartactBm.NAME,
				// activiter.get(Activiter.ACTIVITER_NAME));
				MenberCardStartactBm bm = bmService.findMenberCardStarctBmForOne(ret, whereCodis,
						MenberCardStartactBm.MP);
				if (bm == null) {
					MenberCardStartactBm newBm = new MenberCardStartactBm();
					newBm.set(MenberCardStartactBm.MP, activiter.get(Activiter.ACTIVITER_MOBILE));
					newBm.set(MenberCardStartactBm.NAME, activiter.get(Activiter.ACTIVITER_NAME));
					newBm.set(MenberCardStartactBm.ORDERNUM, activiter.get(Activiter.SIGN_CODE));
					newBm.set(MenberCardStartactBm.RECORD_ID, activiter.get(Activiter.HD_ID));
					newBm.set(MenberCardStartactBm.BM_TIME, Integer.valueOf(nowStr));
					newBm.save();
				}
			}
			renderJsp("impt.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void data() {
		Integer pageErr = getParaToInt(0);
		Integer pageRight = getParaToInt(1);
		try {
			int pageSize = 3;
			VoPageHelper<ActiviterVO> helper = new VoPageHelper<ActiviterVO>();
			Page<ActiviterVO> errPage = helper.paginate(pageErr, pageSize, errVos);
			Page<ActiviterVO> rightPage = helper.paginate(pageRight, pageSize, rightVos);
			setAttr("errPage", errPage);
			setAttr("errIsFirst", errPage.isFirstPage());
			setAttr("errIsLast", errPage.isLastPage());
			setAttr("rightPage", rightPage);
			setAttr("rightIsFirst", rightPage.isFirstPage());
			setAttr("rightIsLast", rightPage.isLastPage());
			renderJsp("result.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Before(POST.class)
	public void print() {
		Long id = getParaToLong("id");
		ActiviterService activiterService = enhance(ActiviterService.class);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(Activiter.ID, id);
		Activiter activiter = activiterService.getActiviterByCoditionForOne(params);
		boolean isPrint = outPrint(activiter);
		JSONObject json = new JSONObject();
		if (isPrint) {
			json.put("msg", "打印成功");
		} else {
			json.put("msg", "打印失败");
		}
		renderJson(json.toJSONString());
	}

	private boolean outPrint(Activiter activiter) {
		UserInfor userInfor = new UserInfor();
		userInfor.setuName(activiter.getStr(Activiter.ACTIVITER_NAME));
		userInfor.setCompany(activiter.getStr(Activiter.ENTERPRISE));
		SeatService seatService = enhance(SeatService.class);
		SeatInfo seatInfo = seatService.findSeatInfoByActiviterID(activiter.getLong(Activiter.ID));
		if (seatInfo == null) {
			userInfor.setSeatNO("V");
		} else {
			userInfor.setSeatNO("V" + seatInfo.getStr(SeatInfo.SEAT_NO));
		}
		try {
			PrintUtil.genc_print(userInfor);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
